import datetime
from functools import wraps
from django.http import JsonResponse
from django.utils.decorators import available_attrs
from core.tools.models import ShortMsg


def verify_tel():
    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request):
            if request.POST.get("account"):
                return view_func(request)
            code = request.POST.get("ver_code")
            tel = request.POST.get("tel")
            info = ShortMsg.objects.filter(code=code, tel=tel)
            if info.exists():
                info_obj = info.first()
                if info_obj.status:
                    info_obj.status = False
                    info_obj.save()
                    return view_func(request)
                else:
                    context = {"msg": "此验证码已经使用过了", "status": "error"}
                    return JsonResponse(context)
            else:
                context = {"msg": "验证码不正确", "status": "error"}
                return JsonResponse(context)

        return _wrapped_view

    return decorator
